<template>
  <div class="staff_quanlified_rate">
    <one-title title="员工送检合格率" @refreshData="refresh"></one-title>
    <div class="fixed_top_56">
      <div class="multiple_search">
        <div class="search_item">
          <div class="select_label">
            选择班组：
          </div>
          <div class="search_wrapper">
            <el-select
              v-model="workgroupId"
              placeholder="请选择班组"
              @change="handleGroup"
              size="small">
              <el-option
                v-for="(item,index) in workGroup"
                :key="index"
                :label="item.NAME"
                :value="item.ID">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="search_item">
          <div class="select_label">
            工作中心：
          </div>
          <div class="search_wrapper">
            <el-select
              v-model="workCenterIds"
              multiple
              collapse-tags
              placeholder="选择工作中心"
              size="small">
              <el-option
                v-for="(item,index) in workCenter"
                :key="index"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="search_item">
          <span class="search_label">工序完成日期：</span>
          <el-date-picker
            v-model="completionDate"
            type="daterange"
            size="small"
            align="right"
            :clearable=false
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
            :picker-options="pickerOptions">
          </el-date-picker>
        </div>
        <div class="mes_btn">
          <el-button
            type="primary"
            icon="el-icon-search"
            class="search_btn"
            @click="getDetailData">
          </el-button>
        </div>
      </div>
      <div class="chart_box">
        <div ref="myChart" class="chart_wrapper"></div>
      </div>
      <div class="table_container">
        <el-table
          :data="listData"
          ref="mesTable"
          max-height="440"
          v-loading="isLoading"
          border
          stripe
          @sort-change="_sort"
          tooltip-effect="dark">
          <el-table-column
            label="员工名称"
            width="200">
            <template slot-scope="scope">
              {{scope.row.staffName + '/' + scope.row.staffNumber}}
            </template>
          </el-table-column>
          <mes-column
            :key="index"
            v-for="(column, index) in tableColumns"
            :column="column">
          </mes-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>

import tableColumns from './tableColumns'

export default {
  name: 'StaffQuanlifiedRate',
  components: {
    tableColumns
  },
  data() {
    return {
      tableColumns: tableColumns, // 列配置
      isLoading: false, // 加载
      workgroupId: '', // 班组
      workCenterIds: [], // 工作中心
      sortData: {}, // 排序对象
      staff: [], // x轴
      completeQuantity: [], // 合格数
      wasteQuantity: [], // 不合格数
      quanlifiedRate: [], // 合格率
      completionDate: [
        this.moment(window.serverTime).subtract(1, 'months').format('YYYY-MM-DD 00:00:00'),
        this.moment(window.serverTime).format('YYYY-MM-DD 23:59:59')
      ],
      pickerOptions: this.$dateConfig.pickerOptions // 日期格式的快捷键配置项
    }
  },
  computed: {
    // 班组
    workGroup() {
      return this.$store.state.staffQuanlifiedRate.workGroup
    },
    // 工作中心
    workCenter() {
      return this.$store.state.staffQuanlifiedRate.workCenter.list
    },
    // 图表数据
    listData() {
      return this.$store.state.staffQuanlifiedRate.listData || []
    },
    // 送检合格率
    passRate() {
      return this.listData.map(item => {
        let num = (item.completeQuantity / item.inputQuantity * 100)
        if (isNaN(num)) num = 0
        return num.toFixed(2)
      })
    },
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      Promise.all([this.getWorkGroup(), this.getWorkCenter()]).then(() => {
        setTimeout(() => {
          this.getDetailData()
        }, 1000)
      })
    },
    // 班组
    handleGroup() {
      this.getWorkCenter()
    },
    // 获取班组列表
    getWorkGroup() {
      this.$store.dispatch('saveData', {
        method: 'get',
        url: 'a/workgroup/workgroup/listfields/id,name',
        module: 'staffQuanlifiedRate',
        state: 'workGroup'
      }).then(res => {
        // 默认选中第一个班组
        this.workgroupId = res[0].ID
        this.getWorkCenter()
      })
    },
    // 获取工作中心
    getWorkCenter() {
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/workcenter/workcenter/list',
        data: {
          pageNo: 1,
          pageSize: 999,
          query: {
            workgroupId: this.workgroupId
          }
        },
        module: 'staffQuanlifiedRate',
        state: 'workCenter'
      }).then(res => {
        this.workCenterIds = res.list.reduce((pre, cur) => [...pre, cur.id], [])
      })
    },
    // 刷新
    refresh() {
      this.$refs.mesTable.clearSort()
      this.searchData = {}
      this.sortData = {}
      this.getDetailData()
      this.completionDate = [
        this.moment(window.serverTime).subtract(1, 'months').format('YYYY-MM-DD 00:00:00'),
        this.moment(window.serverTime).format('YYYY-MM-DD 23:59:59')
      ]
    },
    // 初始化方法
    getDetailData() {
      this.isLoading = true
      let postData = {
        method: 'post',
        url: 'a/turnoverworkstage/turnoverWorkstage/staffquanlifiedrate',
        data: {},
        module: 'staffQuanlifiedRate',
        state: 'listData'
      }
      if (this.workgroupId) {
        postData.data.workgroupId = this.workgroupId
      }
      if (this.workCenterIds.length) {
        postData.data.workcenterIds = this.workCenterIds.join(',')
      }
      if (this.completionDate.length > 0) {
        postData.data.beginWorkStageDate = this.completionDate[0]
        postData.data.endWorkStageDate = this.completionDate[1]
      }
      if (Object.keys(this.sortData).length > 0) {
        postData.data.sort = this.sortData
      }
      this.$store.dispatch('saveData', postData).then(res => {
        // 初始化图表数据
        this.echartsData()
        // 设置图表滚动
        let dataZoom = [
          {
            type: 'slider',
            show: false,
            showDetail: false,
            start: 0,
            end: 100,
            bottom: 10,
            height: 16,
            handleStyle: {
              /*手柄的样式*/
              color: '#fff',
              borderWidth: 2,
              borderColor: '#a1b1c1'
            },
          }
        ]
        let max = 12
        if (res.length >= max) {
          let end = Math.floor(max / res.length * 100)
          dataZoom.forEach(item => {
            item.end = end
            item.show = true
          })
        }
        this.drawLine(dataZoom)
      }).finally(() => {
        this.isLoading = false
      })
    },
    // 图表所需数据
    echartsData() {
      this.staff = [] // x轴
      this.wgroupName = [] // 班组
      this.completeQuantity = [] // 合格数
      this.wasteQuantity = [] // 不合格数
      this.quanlifiedRate = [] // 送检合格率
      this.listData.forEach(item => {
        this.staff.push(item.staffName + '/' + item.staffNumber || '')
        this.completeQuantity.push(item.completeQuantity || 0)
        this.wasteQuantity.push(item.wasteQuantity || 0)
        this.quanlifiedRate.push(item.quanlifiedRate || 0)
      })
    },
    // 绘制图表
    drawLine(dataZoom) {
      let myChart = this.$echarts.init(this.$refs.myChart)
      myChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {type: 'shadow'},
          padding: 10,
          textStyle: {fontSize: 12},
          backgroundColor: 'rgba(0, 0, 0, 0.85)',
          formatter: (param) => {
            return param[0].name + '<br />' +
              param[0].marker + param[0].seriesName + ': ' + param[0].value + '<br />' +
              param[1].marker + param[1].seriesName + ': ' + param[1].value + '<br />' +
              param[2].marker + param[2].seriesName + ': ' + param[2].value + '%'
          }
        },
        // 缩放,滚动
        dataZoom: dataZoom,
        // 画板边距
        grid: {
          left: '60',
          right: '60'
        },
        legend: {
          data: ['合格数', '不合格数', '送检合格率'],
          itemWidth: 24,
          itemHeight: 10,
        },
        xAxis: [
          {
            type: 'category',
            data: this.staff,
            // x轴轴线颜色和宽度
            axisLine: {
              lineStyle: {
                color: '#dcdfe6',
                width: 2
              }
            },
            // x轴字体颜色
            axisLabel: {
              show: true,
              textStyle: {
                color: 'rgba(0, 0, 0, 0.65)'
              }
            },
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '次数',
            // Y轴虚线
            splitLine: {
              lineStyle: {
                color: 'rgba(0, 0, 0, 0.1)',
                width: 1,
                type: 'dashed'
              }
            },
            // y轴轴线
            axisLine: {show: false},
            //y轴刻度线
            axisTick: {show: false},
          },
          {
            type: 'value',
            name: '合格率',
            min: 0,
            max: 100,
            splitLine: {
              'show': false,
              lineStyle: {
                color: '#333',
                width: 1,
                type: 'dashed',
              }
            },
            axisLine: {'show': false},
            axisTick: {'show': false},
            axisLabel: {formatter: '{value}%'}
          }
        ],
        // 数据
        series: [
          {
            name: '合格数',
            type: 'bar',
            data: this.completeQuantity,
            stack: '数量',
            barMaxWidth: 160, // 柱子的宽度
            barMinWidth: 10,
            itemStyle: {
              normal: {
                color: '#1890ff',
                opacity: 0.85
              }
            }
          },
          {
            name: '不合格数',
            type: 'bar',
            stack: '数量',
            data: this.wasteQuantity,
            barMaxWidth: 160,
            itemStyle: {
              normal: {
                color: '#fbda56',
                opacity: 0.85
              }
            }
          },
          {
            name: '送检合格率',
            type: 'line',
            data: this.passRate,
            yAxisIndex: 1,
            label: {
              show: false,
              formatter: '{c}%',
              fontSize: 12
            },
            itemStyle: {
              normal: {
                color: '#f04864',
              }
            }
          },
        ]
      })
    },
    // 排序
    _sort(obj) {
      this.sortData = this.$getSortOrder(obj)
      this.getDetailData()
    }
  }
}
</script>

<style scoped lang="less">
  .staff_quanlified_rate {
    .chart_box {
      padding: 0 20px;
      .chart_wrapper {
        width: 100%;
        height: 500px;
        box-sizing: border-box;
        border: 1px solid #dcdfe6;
        margin-bottom: 20px;
        padding-top: 20px;
      }
    }
    .table_container{
      padding-bottom: 40px;
    }
  }
</style>
<style lang="less">
  .staff_quanlified_rate {
    .search_wrapper {
      .el-select {
        .el-tag--mini {
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 123px;
        }
      }
    }
  }
</style>
